package produce_consume;

/**
 * 一对一生产消费
 *
 * @date 2020/3/9 23:09
 */
public class Code01_SimplePC {
    private final Object LOCK = new Object();
    private boolean isProduced = false;
    private int counter = 0;

    public void produce() throws InterruptedException {
        while (true) {
            synchronized (LOCK) {
                if (isProduced) {
                    LOCK.wait();
                }else {
                    System.out.println(Thread.currentThread().getName()+"生产了:" + (++counter));
                    isProduced = true;
                    LOCK.notifyAll();
                    Thread.sleep(10);
                }
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            synchronized (LOCK) {
                if (!isProduced) {
                    LOCK.wait();
                }else {
                    System.out.println(Thread.currentThread().getName()+"消费了:" + (counter));
                    isProduced = false;
                    LOCK.notifyAll();
                    Thread.sleep(10);
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Code01_SimplePC pc = new Code01_SimplePC();
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                try {
                    pc.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"P"+i).start();

            new Thread(() -> {
                try {
                    pc.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"C"+i).start();
        }
    }
}
